package atom.loader.library {
	
	import atom.loader.ILoader;
	import atom.loader.types.AssetData;
	import atom.loader.types.AssetLoader;
	import atom.loader.types.AssetMultimedia;
	import atom.loader.types.AssetTypes;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	/**
	 * ...
	 * @author Jorge Braccini
	 */
	public dynamic class LibraryLoader extends EventDispatcher implements ILoader {
		
		private var _library:Object;
		private var _assets:Array;
		
		private var _cur:int = 0;
		
		public function LibraryLoader(assets:Array = null) {
			if (assets) _assets = assets;
			init();
		}
		
		public function load():void {
			_cur = 0;
			if (_assets.length > 0) process();
		}
		
		public function cancel():void {
			
		}
		
		public function reload():void {
			
		}
		
		public function destroy():void {
			init();
		}
		
		public function addAsset(id:String, url:String, contentType:String = null):AssetLoader {
			var loader:AssetLoader;
			
			if (!contentType) contentType = AssetTypes.getContentTypeByPath(url);
			switch(contentType) {
				case AssetTypes.TEXT:			loader = new AssetData(id, url); break;
				case AssetTypes.MULTIMEDIA:		loader = new AssetMultimedia(id, url); break;
			}
			
			trace("addItem id: " + id + " url: " + url + " contentType: " + contentType + " | " + loader);
			this[id] = loader;
			_assets.push(loader);
			return loader;
		}
		
		public function getAsset(id:String):* {
			var loader:AssetLoader = this[id];
			return loader.content;
		}
		
		public function removeAsset(id:String):void {
			var loader:AssetLoader = this[id];
				loader.destroy();
				delete this[id];
		}
		
		/**
		 * Protected Methods
		 */
		
		protected function process():void {
			var loader:AssetLoader = _assets[_cur];
				loader.addEventListener(Event.COMPLETE, handleAssetLoaded);
				loader.load();
		}
		
		protected function next():void {
			if (_cur + 1 < _assets.length) {
				_cur++;
				process();
				
			} else finish();
		}
		
		protected function finish():void {
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		protected function get currentId():int { return _cur; }
		
		public function get ready():Boolean { return false; }
		
		/**
		 * Private Methods
		 */
		
		private function init():void {
			_library = { };
			_assets = [];
		}
		
		private function handleAssetLoaded(e:Event):void {
			next();
		}
		
	}

}